package com.hmdp.askPack.interceptors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.askPack.constants.MyRedisConstants;
import com.hmdp.askPack.threadLocals.MyUserHolder;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MyRefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public MyRefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从请求头中获取token
        String token = request.getHeader("authorization");
        // token为空，说明未登录或未携带token，即请求未携带有效的身份验证信息，拦截
        if (StrUtil.isBlank(token)) {
            return true;
        }

        // 2. 根据token从redis中获取用户信息
        String key = MyRedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        // 用户信息为空，说明令牌无效或会话已过期, 拦截
        if (userMap.isEmpty()) {
            return true;
        }

        // 3. 存储用户信息至threadLocal
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        MyUserHolder.setUser(userDTO);

        // 4. 跟新redis中user信息的持续时间
        stringRedisTemplate.expire(key, MyRedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 如果令牌有效且用户信息存在，返回true，允许请求继续处理
        return true;
    }
}
